package com.fairytask.ui
{
	import com.fairytask.data.Record;
	import com.fairytask.data.RecordObject;
	import com.fairytask.engine.GameStage;
	import com.fairytask.engine.components.list.List;
	import com.fairytask.engine.components.list.ListItem;
	import com.fairytask.engine.components.tab.TabBar;
	import com.fairytask.engine.components.tab.TabEvent;
	import com.fairytask.engine.define.RecordDefine;
	import com.fairytask.engine.utils.IO;
	import com.fairytask.event.LogicEvent;
	import com.fairytask.net.CustomToClientEvent;
	import com.fairytask.resource.StaticIni;
	import com.fairytask.ui.base.FrameUI;
	
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TextEvent;

	/**
	 * 任务追踪表
	 * @author yangj
	 **/
	 
	
	public class TaskTraceUI extends FrameUI
	{
		private static var _self			:TaskTraceUI;
		
		//判断是否在打开状态
//		public var isShow          :Boolean	=	false;
		public var tabBar			:TabBar;					//可接任务和已接任务的切换
		public var curList			:List;						//已接list的显示务中所有的任务Id	
		public var bg				:MovieClip;					//半透明背景
		public var canList			:List;						//可接list的显示
		
		
		private var _currentTab	:int		=	0;	//true：任务追踪表  false：可接表
		//可接判断
		private var canBind		:Boolean	=	true;
		private var _arrRecord		:Array		=	new Array(); // 用于存储任务记录表中所有的的任务Id号
		private var _arrCan		:Array		=	new Array(); //用于存储可接任
		private var _unbindArray	:Array		=	[]; //解绑 
		
		public static function getInstance():TaskTraceUI
		{
			if(_self == null)
			{
				_self	=	new TaskTraceUI();
			} 
			return _self;
		}
		
		public function TaskTraceUI(popUI:Boolean = false)
		{
			super(popUI);
			var tips	:String	=	StaticIni.getSwfLangStr("1000000417");
			//添加不同的任务列表，用list来添加
			curList	=	new List(200,108,true,[{label:tips,height:20,skin:""}],"","","left");
			canList	=	new List(200,108,true,[{label:tips,height:20,skin:""}],"","","left");

			addChild(curList);
			curList.x	=	0;
			curList.y	=	30;
			addChild(canList);
			canList.x	=	0;
			canList.y	=	30;
			init();
			initEvent();
		}
		

		
		private function init():void
		{
			//给tabbar添加点击事件
			tabBar.addEventListener(TabEvent.TAB_CLICK,onTab);
			curList.visible	=	true;
			canList.visible	=	false;
			
		}
		
		/**
		 * TabBar切换 
		 * @param evt
		 * 
		 */	
		private function onTab(evt:TabEvent):void
		{
			_currentTab	=	evt.item.id;
			if(_currentTab == 0)
			{
				curList.visible =	true;
				canList.visible =	false;
			}
			else
			{
				curList.visible	=	false;
				canList.visible	=	true;
			}
		}
		
		
		
		private function initEvent():void
		{
			//玩家加载完成后进行绑定
			//model.addEventListener(LogicEvent.DATA_READY,onDataReady);
			
			//计时类任务状态跟新
			/*model.addEventListener(CustomToClientEvent.SERVER_CUSTOMMSG_TASK_TIME,onTimeTaskChage);
			model.addEventListener(CustomToClientEvent.SERVER_CUSTOMMSG_CONTROL_MOVE,findNpc);*/
			//任务追踪
			curList.addEventListener(TextEvent.LINK,onTextLink);
			canList.addEventListener(TextEvent.LINK,onTextLink);
		}
		
		/**
		 *收到消息移动到指定坐标 
		 * @param evt
		 * 
		 */		
		
		private function findNpc(evt:CustomToClientEvent):void
		{
			//Player.instance.closeTo(evt.pList.shift(),evt.pList.shift());
		}
		
		
		
		/**
		 * 追踪内容点击 
		 * @param evt
		 * <a href='event:1,12010101,2'> 
			：1代表 1皇城寻路 2野外寻路
			1后面ID是NPCID，2后面只要填场景号,3 代表打开世界地图
		 */
		private function onTextLink(evt:TextEvent):void
		{
			var lnkArr	:Array	=	evt.text.split(",");
			if(lnkArr[0]=="-1")
			{
				var TaskId:int = int(lnkArr[1]);
				if(TaskId>0)
				{
					//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_DAILY_TASK_COMPLETE_ATONCE,TaskId);
				}
				return;
			}
			if(lnkArr[0]=="3")
			{
				WorldMapUI.getInstance().show();
				return;
			}
			var npcData	:Object	=	StaticIni.getIniObj(lnkArr[1]);
			dispatchEvent(new MouseEvent(MouseEvent.CLICK));
			if(npcData["SceneID"]==model.scene.ConfigID.toString())
			{
//				Player.instance.closeTo(npcData.SiteX,npcData.SiteY);
				//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_SYN_WALKED_TIME,Player.instance.x,Player.instance.y);
				//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_MOVE_TO_NPC,int(lnkArr[1]));
			}
			else
			{
				if(lnkArr[0]=="2")
				{
					//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_MOVE_OTHER_SCENE,int(lnkArr[1]));
				}
				else
				{
					//NetMgr.sendCustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_MOVE_OTHER_SCENE,int(npcData["SceneID"]),int(lnkArr[1]));
				}
			}
		}
		
		private function onDataReady(evt:LogicEvent):void
		{
			if(!canBind)
			{
				return;
			}
			canBind	=	false;
			IO.traceLog("数据绑定被执行================");
			//任务步骤的绑定
			bindManager.BindRecord(model.scene,RecordDefine.TASK_STEP, onAddRec, onRemoveRec);
			//可接任务
			bindManager.BindRecord(model.scene,RecordDefine.TASK_CAN_ACCEPT,onAddCanRec,onRemoveCanRec);
			//bindManager.BindRecord(model.scene,RecordDefine.TASK_STEP,onStepRec,onRemoveStepRec);
		}
		
		/**
		 * 计时类任务状态跟新 
		 * @param evt
		 * 
		 */		
		private function onTimeTaskChage(evt:CustomToClientEvent):void
		{
//			var curItem : TreeItem = treeCur.getItemById(evt.pList.shift());
//			curItem.onTimerOver(null);
//			curItem.timeTxt.htmlText = "<font color='#FF0000'>" + StaticIni.getSwfLangStr("4002006530") + "</font>";
		}
		
		/**
		 * 对任务步骤表进行显示
		 */
		private function onAddRec(key:String,pList:RecordObject):void
		{
			
			/*
			//任务步骤表
			Record_Declare_Begin( Task_Step );
			Column_Declare_Int( Id, 0 );				 //任务编号
			Column_Declare_Int( Step, 1 );				 //任务步骤
			Column_Declare_Int( Key, 2 );				 //关键字
			Column_Declare_Int( Cur, 3 );				 //当前完成度
			Column_Declare_Int( Total, 4 );				 //总进度
			Record_Declare_End
			*/
			if(pList != null)
			{
				_unbindArray.push([pList,bindManager.BindObjProp(pList,"3",onItemChange,[key])]);	//"3" 当前完成度
				
			}
		}
		/**
		 *当“3”列数据发生变化的时候 
		 * @param key
		 * @param val
		 * @param List
		 * 
		 */		
		private function onItemChange(key:String,val:int,List:Array):void
		{
			
			//取特定内容来更新
			var stepRecord	:Record	=	model.scene.GetRecordEx(RecordDefine.TASK_STEP);
			var line:String	=	List[0];
			var valR	:RecordObject	=	stepRecord.GetProperties(line);
			var TaskId		:int	=	valR.GetProperties("0");			//任务的id
			var text:String 	    =	StaticIni.getSwfLangStr("TaskName_" + TaskId);
			var taskComplete:int	=	valR.GetProperties("4");
			var showType:int	=	int(StaticIni.getIniVar(TaskId,"ShowType"));
			var taskCompleteFlag:int = 0;
//			if(taskComplete==1)
//			{
//				text+= StaticIni.getSwfLangStr("TaskAnswerSuc_" + TaskId);
//			}
			text += "<br>";
			var step:int	=	valR.GetProperties("1");
			var num:int		=	valR.GetProperties("3");
			if(num == taskComplete)
			{
				text += StaticIni.getSwfLangStr("1000000020");
				taskCompleteFlag = 1;
				
			}
			else
			{
				text += StaticIni.getSwfLangStrVar("TaskSummar_"+TaskId,[num]);
			}
			text += "<br>";
			text += StaticIni.getSwfLangStrVar("TaskStep_"+TaskId + "_"+step.toString(),[num]) + "<br>";
			var complete:String	=	StaticIni.getIniVar(TaskId,"CompleteAtOnce");
			//如果有立即完成的任务就添加立即完成选项
			if(complete!=null)
			{
				var once:String = StaticIni.getSwfLangStrVar("1000000034",[createLink(TaskId)]);
				text += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
				text += once + "<br>";
			}
			var pos:int = findRecord(int(line),_arrRecord);
			if(pos==-1)
			{
				IO.traceLog("tasktrace 任务内容",text);
				var listItem:ListItem	=	new ListItem(text,200,30);
				_arrRecord.push([showType,listItem,int(line),taskCompleteFlag]);
			}
			else
			{
				var listItem1:ListItem = _arrRecord[pos][1];
				_arrRecord[pos][3] = taskCompleteFlag;
				listItem1.label	=	text;
				
			}
			refushList(curList,_arrRecord);
		}
		
		/**
		 *找到元素在数组中的位置 
		 * @return 
		 * 
		 */		
		private function findRecord(pos:int,arr:Array):int
		{
			for(var i:int=0;i<arr.length;i++)
			{
				if(arr[i][2] == pos)
				{
					return i;
				}
			}
			return -1;
		}
		
		
		/**
		 *对任务的列表进行刷新重新显示
		 * 按照 1，主线任务在前，支线任务在后 
		 * 
		 */		
		private function refushList(list:List,arr:Array):void
		{
			list.listData = null;
			arr.sort(defineSort);
			var tips	:String	=	StaticIni.getSwfLangStr("1000000417");
			list.listData = [{label:tips,height:25,skin:""}];
			for(var i:int=0;i<arr.length;i++)
			{
				list.addItem(arr[i][1]);	
			}
		}
		
		/**
		 *自己定义一个数组的排序的算法 
		 * 
		 */		
		private function defineSort(arr1:Array,arr2:Array):Number
		{
			//首先是已完成在前面
			if(arr1[3]>arr2[3])
			{
				return -1;
			}
			
			if(arr1[3]==arr2[3])
			{
				//如果是主线排在前面
				if(arr1[0]>arr2[0])
				{
					return 1;	
				}
				else if(arr1[0]==arr2[0])
				{
					return 0;
				}
				else
				{
					return -1;
				}
			}
			if(arr1[3]<arr2[3])
			{
				return 1;
			}
			return 0;
		}
		
		
		/**
		 *	创建超链接 
		 * @param str
		 * @return 
		 */		
		private function createLink(taskId:int):String
		{
			var link:String;
			link	="<a href=\"event:"+ "-1," + taskId;
			link	+="\"><u>";
			link	+=	StaticIni.getSwfLangStr("1000000012");
			link	+="</u></a>";
			return link;
		}
		
		
		
		/**
		 * 删除已接任务
		 * @param key
		 * @param val
		 * 
		 */		
		private function onRemoveRec(key:String,val:RecordObject):void
		{
			if(val !=null)
			{
				
				var TaskId:int	=	val.GetProperties("0");
				var pos:int = findRecord(int(key),_arrRecord);
				if(pos==-1)
				{
					return;	
				}
				var listItem:ListItem	=	_arrRecord[pos][1];
				_arrRecord.splice(pos,1);
				var display:DisplayObject	=	listItem as DisplayObject;
				curList.removeItem(display);
				var i:int;
				for each(var itemBind:Array in _unbindArray)
				{
					if((itemBind[0] as RecordObject).GetProperties("0")==val.GetProperties("0"))
					{
						bindManager.UnbindProp(itemBind.shift(),itemBind.shift(),itemBind.shift());
						_unbindArray.splice(i,1);
						break;
					}
					i++;
				}
			}
		}
		
		/**
		 *可接任务进行显示 
		 * 
		 */
		private function onAddCanRec(key:String,val:RecordObject):void
		{
			/*
			可接任务表
			Record_Declare_Begin( Task_Can_Accept );
			Column_Declare_Int( Id, 0);
			Column_Declare_Int(ShowType,1);
			Record_Declare_End
			*/
			if(val != null)
			{
				var TaskId:int	=	val.GetProperties("0");
				var type	:int	=	int(StaticIni.getIniVar(TaskId,"Type"));
				var showType:int	=	int(StaticIni.getIniVar(TaskId,"ShowType"));
				if(type!=8)
				{
					var text:String	=	StaticIni.getSwfLangStr("TaskName_" + TaskId) +"<br>" + StaticIni.getSwfLangStrVar("TaskSummar_"+TaskId,[0])+ "<br>"+StaticIni.getSwfLangStrVar("TaskAccept_"+TaskId,[0]) + "<br>";
					var listItem:ListItem	=	new ListItem(text,200,30);
					var pos:int = findRecord(int(key),_arrCan);
					if(pos==-1)
					{
						IO.traceLog("tasktrace 任务内容",text);
						_arrCan.push([showType,listItem,int(key),0]);
					}
					else
					{
						var listItem1:ListItem = _arrCan[pos][1];
						listItem1.label	=	text;
						
					}
					refushList(canList,_arrCan);
				}
				

			}
		}
		
		/**
		 *删除可接任务 
		 * @param key
		 * @param val
		 * 
		 */		
		private function onRemoveCanRec(key:String,val:RecordObject):void
		{
			
			if(val!=null)
			{
				var TaskId:int	=	val.GetProperties("0");
				var type	:int	=	int(StaticIni.getIniVar(TaskId,"Type"));
				if(type!=8)
				{
					var pos:int = findRecord(int(key),_arrCan);
					if(pos==-1)
					{
						return;	
					}
					var listItem:ListItem	=_arrCan[pos][1];
					_arrCan.splice(pos,1);
					var display:DisplayObject	=	listItem as DisplayObject;
					canList.removeItem(listItem);
				}
				
			}
		}
		
		
	
		
		/**
		 * 在指定位置添加字符串 
		 * @param char
		 * @param value
		 * @param position
		 * @return 
		 * 
		 */		
		private function addStrAt(char:String, value:String, position:int):String
		{
			if (position > char.length)
			{  
				position = char.length;  
			}  
			var firstPart:String = char.substring(0, position);  
			var secondPart:String = char.substring(position, char.length);  
			return (firstPart + value + secondPart);
		}
		

		
		/**
		 *	任务追踪 
		 * @param key
		 * @param pList
		 * 
		 */		
	
		
		/**
		 * 删除完成或者放弃的当前任务id  
		 * @param key
		 * @param pList
		 * 
		 */		
	
		
		/**
		 * 添加可接任务 
		 * @param key
		 * @param pList
		 * 
		 */
	
		
		/**
		 * 删除完成或者放弃的可接任务id  
		 * @param key
		 * @param pList
		 * 
		 */		 
		
		
		
		/**
		 * 任务进度跟踪 
		 * @param key
		 * @param val
		 * @param pList
		 * 
		 */		


		/**
		 * 任务显示跟新 
		 * @param type 0:当前任务 1:可接任务
		 * 
		 */	
		
		
		
		
		override public function hide(e:*=null):void
		{
			super.hide(e);
		}
		
		/**
		 *	任务追踪 可用不可用			For新手引导 
		 * @param bool
		 * 
		 */		
		public function openClose(component:String,isOpen:Boolean):void
		{
			this[component].mouseChildren	=	isOpen;
		}
		
		/**
		 * 重写显示 
		 * @param space
		 * @param onshow
		 * @param argc
		 * 
		 */		
		override public function show(space:String=BACKLAYER, onshow:Function=null):void
		{
			super.show(space,onshow);
		}
		
		/**
		 * 场景变化改变位置 
		 * 
		 */
		override protected function stageReSize(evt:Event=null):void
		{
			this.x	=	initX - GameStage.x;
			this.y = 	initY - GameStage.y;
		}
		
	}
}